package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.json.JacksonObjectMapper;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import io.swagger.models.auth.In;
import org.apache.poi.ss.usermodel.DataFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.sky.json.JacksonObjectMapper.DEFAULT_DATE_TIME_FORMAT;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!s.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }


    /**
     * 员工添加服务层
     */
    @Override
    public void insertEmp(EmployeeDTO employeeDTO) {
        //1添加缺失属性
        Employee emp = new Employee();
        //工具类  将源数据拷贝到新类型中  通过名字和类型匹配拷贝。
        BeanUtils.copyProperties(employeeDTO, emp);
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        //TODO


        emp.setCreateUser(BaseContext.getCurrentId());
        emp.setUpdateUser(BaseContext.getCurrentId());


        emp.setStatus(StatusConstant.ENABLE);//设置状态 开启

        //2设置默认密码 并MD5加密
        emp.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //3调用持久层  将数据插入数据库


        employeeMapper.insertEmp(emp);

    }


    /**
     * 分页查询
     */
    @Override
    public PageResult getEmpInfoOfPage(String name, Integer page, Integer pageSzie) {
        PageHelper.startPage(page, pageSzie);
        List<Employee> temp = employeeMapper.getEmpInfoOfPage(name);
        Page<Employee> page1=(Page<Employee>)temp;
        return new PageResult(page1.getTotal(),page1.getResult());
    }

    /**
     * 修改员工账号可用状态
     */
    @Override
    public void statusOrStop(Integer status, Integer id) {

        //链式编程
        Employee employee= Employee.builder()
                .status(status)
                .id(id.longValue())
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.updateEmpById(employee);

    }

    /**
     * 根据员工ID 查询员工信息
     */
    @Override
    public Employee getEmpById(Long id) {

        return employeeMapper.getEmpById(id);
    }
    /**
     * 根据ID 修改员工
     */
    @Override
    public void updateEmpById(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.updateEmpById(employee);
    }
}
